#include "Sqlist.h"

Status ListInitial_sq(Sqlist *L)
{
    L->elem=(int*)malloc(LIST_INIT_SIZE*sizeof(int));
    if(!L->elem) exit(OVERFLOW);
    L->length=0;
    L->listsize=LIST_INIT_SIZE;
    return OK;
}// ListInitial_sq

Status ListInsert_sq(Sqlist *L,int i,int e)
{
    if(i<1||i>L->length+1) return ERROR;
    if(L->length>=L->listsize)
    {
        int *newbase=(int*)malloc((L->listsize+LIST_INCREMENT)*sizeof(int));
        if(!newbase) exit(OVERFLOW);
        L->elem=newbase;
        L->listsize+=LIST_INCREMENT;
    }
    int *q=L->elem+i-1;
    int *p=L->elem+L->length-1;
    for(;p>=q;--p)
        *(p+1)=*p;
    *q=e;
    ++L->length;
    return OK;
}// ListInsert_sq

Status ListDelete_sq(Sqlist *L,int i,int *e)
{
    if(i<1||i>L->length) return ERROR;
    *e=L->elem[i-1];
    int *p=L->elem+i-1;
    int *q=L->elem+L->length-1;
    for(;p<q;++p)
    {
        *p=*(p+1);
    }
    --L->length;
    return OK;
}// ListDelete_sq

Status MergeList_sq(Sqlist La,Sqlist Lb,Sqlist *Lc)
{
    int *pa=La.elem;
    int *pb=Lb.elem;
    Lc->length=Lc->listsize=La.length+Lb.length;
    int *pc=Lc->elem=(int*)malloc(Lc->listsize*sizeof(int));
    if(!Lc->elem) exit(OVERFLOW);
    int *La_last=pa+La.length-1;
    int *Lb_last=pb+Lb.length-1;
    while(pa<=La_last&&pb<=Lb_last)
    {
        if(*pa<*pb)
            *pc++=*pa++;
        else
            *pc++=*pb++;
    }
    while(pa<=La_last)
        *pc++=*pa++;
    while(pb<=Lb_last)
        *pc++=*pb++;
    return OK;
}

int main()
{
    Sqlist a,b,c;
    ListInitial_sq(&a);
    ListInitial_sq(&b);
    ListInitial_sq(&c);
    int e=0;

    while(scanf("%d",&e)&&e!=-1)
    {
        ListInsert_sq(&a,a.length+1,e);
    }

    for(int *p=a.elem;p<=a.elem+a.length-1;++p)
        printf("%d\n",*p);

    printf("\n");

    e=0;

    while(scanf("%d",&e)&&e!=-1)
    {
        ListInsert_sq(&b,b.length+1,e);
    }

    for(int *p=b.elem;p<=b.elem+b.length-1;++p)
        printf("%d\n",*p);

    printf("\n");

    MergeList_sq(a,b,&c);

    for(int *p=c.elem;p<=c.elem+c.length-1;++p)
        printf("%d\n",*p);

    return 0;
}
